package com.mars.framework.filter;

import com.alibaba.fastjson.JSONObject;
import com.mars.common.util.RSAUtils;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 功能描述
 *
 * @author 程序员Mars
 * @version 1.0
 * @date 2023-12-08 17:44:47
 */

//@Component
public class RequestHandlerFilter implements Filter {
    @SneakyThrows
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // form-data不校验
        if ("application/x-www-form-urlencoded".equals(request.getContentType())) {
            chain.doFilter(request, response);
            return;
        }
        // 拿到加密串
        String data = new RequestWrapper((HttpServletRequest) request).getBody();
        if (StringUtils.isEmpty(data)) {
            chain.doFilter(request, response);
            return;
        }
        String encryptData = JSONObject.parseObject(data).getString("data");
        // 解析
        String body = RSAUtils.decode(encryptData);
        request = new BodyRequestWrapper((HttpServletRequest) request, body);
        chain.doFilter(request, response);
    }
}
